package bookManage.util;

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;


import Util.TestUtil;
import bookManage.BookTest;
import bookManage.model.CardModel;

public class CardUtil {

	/**
	 * 存放借阅卡的集合
	 */
	public static ArrayList<CardModel> cards = new ArrayList<CardModel>();

	static Scanner sc = new Scanner(System.in);

	/**
	 * 存放借阅卡的文件
	 */
	static String path = TestUtil.creatPath("BookManage", "cards");

	/**
	 * 当前登录的用户名
	 */
	static String user;

	/**
	 * 查看所有借阅卡
	 */
	public void selectAll() {
		for (CardModel card : cards) {
			info(card);
		}
	}

	/**
	 * 借阅卡详情
	 * 
	 * @param card
	 */
	public void info(CardModel card) {
		System.out.println("========================");
		System.out.println("卡号：" + card.getCardId());
		System.out.println("姓名：" + card.getName());
		System.out.println("借阅图书：");
		System.out.println("========================");
	}

	/**
	 * 注册
	 * 
	 * 添加
	 */
	public void add() {
		System.out.println("=========添加==========");
		System.out.print("请输入id：");
		int id = TestUtil.abnormal();
		System.out.print("请输入借阅卡号：");
		String cardId = sc.nextLine();
		System.out.print("请输入姓名：");
		String name = sc.nextLine();
		System.out.print("请输入密码：");
		String pass = sc.nextLine();

		CardModel card = new CardModel();
		card.setId(id);
		card.setCardId(cardId);
		card.setName(name);
		card.setPass(pass);

		cards.add(card);
		System.out.println("添加成功！");
		TestUtil.write(path, cards);
	}

	/**
	 * 登录
	 */
	public void login() {
		System.out.println("=========登录==========");
		System.out.print("请输入借阅卡号：");
		String cardId = sc.nextLine();
		System.out.print("请输入密码：");
		String pass = sc.nextLine();

		if (judge(cardId, pass)) {// 用户名，密码输入正确
			user = cardId;

			System.out.println();
			System.out.println("登录成功！");
			System.out.println();
			
			BookTest bookTest = new BookTest();
			bookTest.userStart();
			
			return;
		}
		System.out.println();
		System.out.println("登录失败！");
		System.out.println();
	}

	/**
	 * 判断用户名密码是否正确
	 * 
	 * @param cardId
	 * @param pass
	 * @return
	 */
	public boolean judge(String cardId, String pass) {
		for (CardModel card : cards) {
			if (card.getCardId().equals(cardId) && card.getPass().equals(pass)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 初始化
	 */
	public static void init() {
		CardModel card = new CardModel();
		card.setId(210001);
		card.setCardId("2107001");
		card.setName("迪迦");
		card.setPass("123456");

		cards.add(card);
		TestUtil.write(path, cards);
	}

	/**
	 * 读取，反序列化
	 */
	static {
		judge();
		cards = TestUtil.read(path);
	}

	/**
	 * 判断文件内是否有内容
	 */
	public static void judge() {
		File f = new File(path);
		if (f.length() == 0) {
			init();
		}
	}
}
